package com.ifinc.common.protocol.i8583.field;

import com.ifinc.common.protocol.i8583.I8583Request;
import com.ifinc.common.utils.StringUtils;
import com.ifinc.common.utils.encode.ByteUtil;

import java.util.Map;

/**
 * User: luotao
 * Date: 13-11-15
 * Time: 13:41
 */
public class FieldBitMap extends AbstractField {

    public FieldBitMap() {
        super(8, false);
    }

    @Override
    public byte[] toByte() {
        byte[] result = new byte[8];
        StringBuilder blockBuilder = new StringBuilder(8);
        Map<Integer, Field> dataMap = i8583Request.getData();
        for (int i = 1; i <= I8583Request.FIELD_LEN; i++) {
            Field field = dataMap.get(i);
            if (field == null) {
                blockBuilder.append(StringUtils.STR_ZERO);
            } else if (field instanceof FieldMac && i8583Request.isNeedMac()) {
                blockBuilder.append(StringUtils.STR_ONE);
            } else if (field.getSrcBytes().length == 0) {
                blockBuilder.append(StringUtils.STR_ZERO);
            } else {
                blockBuilder.append(StringUtils.STR_ONE);
            }
            if (i == 64) {
                System.out.println(1);
            }
            if (i % 8 == 0) {
                byte bit = ByteUtil.makeIntFromBinary(blockBuilder.toString());
                int ss = i / 8 - 1;
                result[ss] = bit;
                blockBuilder = new StringBuilder(StringUtils.STR_SPACE);
            }
        }

        resBytes = result;
        return result;
    }

    @Override
    public byte[] toMacByte() {
        return new byte[0];
    }

    @Override
    public String getFieldType() {
        return VAR;
    }

    @Override
    public boolean isAutoFill() {
        return true;
    }

    @Override
    public int toValue(byte[] data, int index) {
        return 0;
    }
}
